//
//  BookingRegistViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/5/29.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "BookingRegistViewController.h"
#import "BookingDetailsViewController.h"
#import "BookingModel.h"
//下拉框
#import "ComboBoxView.h"
//cell
#import "LiaoyangCell.h"
#import "TuangouCell.h"
#import "QinrenCell.h"
#import "HouniaoCell.h"

@interface BookingRegistViewController ()<UITableViewDataSource,UITableViewDelegate,sendSelectecdIndexDelegate>

{
    ComboBoxView  *_comboBox;
    
    NSInteger _comboxSelectedIndex;
    
    NSInteger _pageIndex;
    
    UIView * _headerView;
    
    BOOL _needRefresh;
    
}
@property (nonatomic, strong) NSMutableArray * dataSource;
/**待处理预约数据源*/
@property (nonatomic, strong) NSMutableArray * waitingDataSource;
/**已处理预约数据源*/
@property (nonatomic, strong) NSMutableArray * completeDataSource;

@property (nonatomic, strong) UITableView * baseTableView;

@property (nonatomic, strong) UISegmentedControl * segmentControl;


@end

@implementation BookingRegistViewController


- (instancetype)init
{
    self = [super init];
    if (self) {
        _dataSource         = [NSMutableArray array];
        _waitingDataSource  = [NSMutableArray array];
        _completeDataSource = [NSMutableArray array];
        
        _comboxSelectedIndex = 0;
        _pageIndex = 1;
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self requestForData];
    [self creatTableView];
    [self creatHeaderView];
    
    
}

//- (void)viewWillAppear:(BOOL)animated
//{
//    [_dataSource removeAllObjects];
//    [_waitingDataSource removeAllObjects];
//    [_completeDataSource removeAllObjects];
//    [self requestForData];
//}

#pragma mark --------- 网络请求-------------
- (void)requestForData
{
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    User *user = [User sharedUser];
    NSDictionary *parameters =  @{@"employee_id":user.employee_id,@"type":@"0",@"pagesize":@"30",@"pageindex":[NSString stringWithFormat:@"%ld",(long)_pageIndex],@"time":[NSString stringWithFormat:@"%ld",(long)_comboxSelectedIndex]};
    NSLog(@"服务预约：%@",parameters);
    [manager GetWithParameters:parameters method:@"search.user.bespeak" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;

        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"服务预约的dictonary :%@",[dictionary description]);


        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            if (_needRefresh) {
                [SVProgressHUD showSuccessWithStatus:@"请求数据中"];
                
                
                [_dataSource removeAllObjects];
                [_waitingDataSource removeAllObjects];
                [_completeDataSource removeAllObjects];
            }

            for (NSDictionary *dataDic in dictionary[@"data"]) {

                BookingModel *bookingModel = [[BookingModel alloc]init];
                [bookingModel setValuesForKeysWithDictionary:dataDic];
            
                [_dataSource addObject:bookingModel];
                
                if ([bookingModel.status integerValue] == 0) {
                    [_waitingDataSource addObject:bookingModel];
                } else {
                    [_completeDataSource addObject:bookingModel];
                }

            }

            [_baseTableView reloadData];

            if ([dictionary[@"total"] integerValue] < 30) {

                //[_personalTableView.footer resetNoMoreData];

                [_baseTableView.footer endRefreshing];
                [_baseTableView.header endRefreshing];
                [_baseTableView.footer noticeNoMoreData];
                return ;
            }



        }
        else
        {

            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }

        [_baseTableView.footer endRefreshing];
        [_baseTableView.header endRefreshing];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        [_baseTableView.footer endRefreshing];
        [_baseTableView.header endRefreshing];
    }];
    
}

- (void)creatHeaderView
{
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 50)];
    
    _headerView.backgroundColor = Lightlightcolor;
    
    [self.view addSubview:_headerView];
    
    //自定义UISegmentedcontrol
    
    _segmentControl=[[UISegmentedControl alloc] initWithFrame:CGRectMake(5, 5, SCREEN_W * 0.7, 40) ];
    [_segmentControl insertSegmentWithTitle:@"待处理预约" atIndex:0 animated:YES];
    [_segmentControl insertSegmentWithTitle:@"已处理预约" atIndex:1 animated:YES];
    _segmentControl.selectedSegmentIndex = 0;
    _segmentControl.momentary = NO;
    _segmentControl.multipleTouchEnabled=NO;
    [_segmentControl addTarget:self action:@selector(segmentIndexChanged) forControlEvents:UIControlEventValueChanged];
    
    [_headerView addSubview:_segmentControl];
    
    [self creatComboBox];
}

- (void)creatComboBox
{
    NSArray *comboBoxDatasource = [[NSArray alloc] initWithObjects:@"全部", @"本周", @"本月", @"最近三月", @"最近半年", @"最近一年", nil];
    
    _comboBox = [[ComboBoxView alloc] initWithFrame:CGRectMake(SCREEN_W - SCREEN_W/4-5, 10, SCREEN_W/4, 200)];
    _comboBox.comboBoxDatasource = comboBoxDatasource;
    _comboBox.backgroundColor = [UIColor clearColor];
    _comboBox.delegate = self;
    [_comboBox setContent:[comboBoxDatasource objectAtIndex:0]];
    
    [self.view addSubview:_comboBox];
}

- (void)creatTableView
{
    _baseTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50, SCREEN_W, SCREEN_H-50-64) style:UITableViewStylePlain];
    
    _baseTableView.delegate = self;
    _baseTableView.dataSource = self;
    _baseTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.view addSubview:_baseTableView];
    
    
    UINib * nib1 = [UINib nibWithNibName:@"LiaoyangCell" bundle:nil];
    [_baseTableView registerNib:nib1 forCellReuseIdentifier:@"liaoyangCell"];
    
    UINib * nib2 = [UINib nibWithNibName:@"TuangouCell" bundle:nil];
    [_baseTableView registerNib:nib2 forCellReuseIdentifier:@"tuangouCell"];
    
    UINib * nib3 = [UINib nibWithNibName:@"QinrenCell" bundle:nil];
    [_baseTableView registerNib:nib3 forCellReuseIdentifier:@"qinrenCell"];
    
    UINib * nib4 = [UINib nibWithNibName:@"HouniaoCell" bundle:nil];
    [_baseTableView registerNib:nib4 forCellReuseIdentifier:@"houniaoCell"];
    

    __weak typeof(self) weakSelf = self;
    [_baseTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    [_baseTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];

    
}
- (void)headerRefresh{
    _needRefresh = YES;
    _pageIndex = 1;
    [self requestForData];
}
- (void)footerRefresh{
    _needRefresh = NO;
    _pageIndex ++;
    [self requestForData];
}


#pragma mark - buttonClickEvent

- (void)segmentIndexChanged
{
    switch (_segmentControl.selectedSegmentIndex) {
        case 0:
        {
            NSLog(@"待处理预约");
            [_baseTableView reloadData];
        }
            break;
        case 1:
        {
            NSLog(@"已处理预约");
            [_baseTableView reloadData];
        }
            break;
        default:
            break;
    }
}

#pragma mark-sendSelectecdIndexDelegate
- (void)sendSelectedIndex:(NSInteger)selectedIndex{
    [_dataSource removeAllObjects];
    [_waitingDataSource removeAllObjects];
    [_completeDataSource removeAllObjects];
    _pageIndex = 1;
    _comboxSelectedIndex = selectedIndex;
    [self requestForData];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    //return [self.dataSource count];
    if (_segmentControl.selectedSegmentIndex == 0) {
        return _waitingDataSource.count;
    }else if (_segmentControl.selectedSegmentIndex == 1) {
        return _completeDataSource.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BookingModel *model;
    NSInteger i ;
    if (_segmentControl.selectedSegmentIndex == 0) {
        model = _waitingDataSource[indexPath.row];
        
    }else if (_segmentControl.selectedSegmentIndex == 1){
        model = _completeDataSource[indexPath.row];
    }
    
    i = [model.type integerValue];
    if (i == 1) {
//        NSLog(@"%ld",(long)i);
        static NSString *CellIdentifier1 = @"liaoyangCell";
        
        LiaoyangCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
    
        if (cell == nil) {
            cell = [[LiaoyangCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1];
        }
        [cell fillCellWithModel:model];
        return cell;

    }else if(i == 2) {
//        NSLog(@"%ld",(long)i);
        static NSString *CellIdentifier2 = @"tuangouCell";
        
        TuangouCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        
        if (cell == nil) {
            cell = [[TuangouCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
        }
        [cell fillCellWithModel:model];
        return cell;
        
    }else if(i == 3) {
//        NSLog(@"%ld",(long)i);
        static NSString *CellIdentifier3 = @"qinrenCell";
        
        QinrenCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier3];
        
        if (cell == nil) {
            cell = [[QinrenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier3];
        }
        [cell fillCellWithModel:model];
        return cell;
        
    }else if(i == 4) {
//        NSLog(@"%ld",(long)i);
        static NSString *CellIdentifier4 = @"houniaoCell";
        
        HouniaoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier4];
        
        if (cell == nil) {
            cell = [[HouniaoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier4];
        }
        [cell fillCellWithModel:model];
        return cell;
        
    }
    
    return 0;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BookingModel *model;
    NSInteger i ;
    if (_segmentControl.selectedSegmentIndex == 0) {
        model = _waitingDataSource[indexPath.row];
        
    }else if (_segmentControl.selectedSegmentIndex == 1){
        model = _completeDataSource[indexPath.row];
    }
    
    i = [model.type integerValue];
    if (i == 1) {
//        NSLog(@"%ld",(long)i);
        return 125;
        
    }else if(i == 2) {
//        NSLog(@"%ld",(long)i);
        return 150;
        
    }else if(i == 3) {
//        NSLog(@"%ld",(long)i);
        return 145;
        
    }else if(i == 4) {
//        NSLog(@"%ld",(long)i);
        return 140;
    }
    
    return 0;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        BookingModel *model;
       // NSInteger i ;
        model = _waitingDataSource[indexPath.row];
        
        BookingDetailsViewController *bookingDetailsViewController = [[BookingDetailsViewController alloc]init];
        
        bookingDetailsViewController.type = YES;
        bookingDetailsViewController.model = model;
        bookingDetailsViewController.title = @"预约详情";
        [self.navigationController pushViewController:bookingDetailsViewController animated:NO];

    }else {
        BookingModel *model;
        // NSInteger i ;
        model = _completeDataSource[indexPath.row];
        
        BookingDetailsViewController *bookingDetailsViewController = [[BookingDetailsViewController alloc]init];
        bookingDetailsViewController.type = NO;
        bookingDetailsViewController.model = model;
        bookingDetailsViewController.title = @"预约详情";
        [self.navigationController pushViewController:bookingDetailsViewController animated:NO];

    }
}

@end
